const DB = require('../db/db');
// 注册
const register = async (registerinfo) => {
    let result1 = await checkphone(registerinfo.phone);
    if (result1) {
        return { msg: '该手机号已被注册', code: 1 }
    } else {
        let result = await DB.insert('user', {
            username: registerinfo.username,
            password: registerinfo.password,
            phone: registerinfo.phone,
            img: registerinfo.img
        })
        if (result.affectedRows > 0) {
            return { msg: '注册成功', code: 0, data: result };
        } else {
            return { msg: '注册失败', code: 1, data: result };
        }
    }
}
const checkphone = async (phone) => {
    let checkSql = `select phone from user where phone = ?`;
    let checkResult = await DB.execute(checkSql, [phone]);
    // console.log(checkResult[0]);
    if (checkResult[0].length > 0) {
        return true;
    } else {
        return false;
    }
}

const checktwo = async (fields1, fields2) => {
    let checkSql = `select password , phone from user where password = ? and phone = ?`;
    let checkResult = await DB.execute(checkSql, [fields1, fields2]);
    console.log(checkResult[0])
    if (checkResult[0].length > 0) {
        return true;
    } else {
        return false;
    }
}
// 登录
const login = async (logininfo) => {
    let result1 = await checktwo(logininfo.password, logininfo.phone);
    console.log(result1)
    if (result1) {
        return { msg: '登录成功', code: 0, data: result }
    } else {
        return { msg: '登录失败，请检查账号密码', code: 1, data: result }
    }
}

// 管理员登录
const adminlogin = async (logininfo) => {
    console.log(logininfo)
    let result = await DB.select('admin', {
        where_and:
            [`username = '${logininfo.username}'`,
            ` password= '${logininfo.password}'`]
    });
    if (result.length > 0) {
        return { msg: '登录成功', code: 0 };
    } else {
        return { msg: '登录失败，请检查账号密码', code: 1, };
    }
}
// 查询
const select = async () => {
    let result = await DB.select('user', {});
    return { msg: '查询成功', code: 0, data: result };
}
// 
const selectbyname = async (param) => {
    let result = await DB.select('user', {
        fields: '*',
        where_and: [`username="${param.username}"`]
    });
    return { msg: '查询成功', code: 0, data: result };
}
module.exports = { register, login, select, selectbyname, adminlogin }